<template>
  <div class="security-knowledge-base">
    <el-card class="knowledge-base-card">
      <template #header>
        <div class="card-header">
          <h2>安全知识库管理</h2>
          <div class="header-actions">
            <el-button type="primary" @click="openCreateArticleDialog" icon="el-icon-plus">
              新建文章
            </el-button>
            <el-dropdown @command="handleHeaderCommand">
              <el-button icon="el-icon-more">
                更多 <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="importArticles">导入文章</el-dropdown-item>
                  <el-dropdown-item command="exportArticles">导出文章</el-dropdown-item>
                  <el-dropdown-item command="refresh">刷新</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </template>

      <!-- 搜索筛选区域 -->
      <div class="search-filter-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              v-model="searchForm.keyword"
              placeholder="搜索标题、标签、关键词"
              prefix-icon="el-icon-search"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-col>
          <el-col :span="5">
            <el-select
              v-model="searchForm.category"
              placeholder="选择分类"
              clearable
              filterable
            >
              <el-option
                v-for="item in categories"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col>
          <el-col :span="5">
            <el-select
              v-model="searchForm.tags"
              placeholder="选择标签"
              multiple
              filterable
            >
              <el-option
                v-for="item in allTags"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-col>
          <el-col :span="5">
            <el-select
              v-model="searchForm.severity"
              placeholder="选择严重级别"
              clearable
            >
              <el-option
                v-for="item in severityOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col>
          <el-col :span="3">
            <el-button type="primary" @click="handleSearch" icon="el-icon-search">
              搜索
            </el-button>
          </el-col>
        </el-row>
        
        <!-- 高级筛选 -->
        <div class="advanced-filter" v-if="showAdvancedFilter">
          <el-row :gutter="20" style="margin-top: 16px;">
            <el-col :span="8">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
              />
            </el-col>
            <el-col :span="6">
              <el-select
                v-model="searchForm.author"
                placeholder="选择作者"
                clearable
                filterable
              >
                <el-option
                  v-for="item in authors"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select
                v-model="searchForm.status"
                placeholder="选择状态"
                clearable
              >
                <el-option label="草稿" value="draft" />
                <el-option label="已发布" value="published" />
                <el-option label="已归档" value="archived" />
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-button @click="resetSearch">重置</el-button>
            </el-col>
          </el-row>
        </div>
        
        <div class="filter-actions">
          <el-button type="text" @click="toggleAdvancedFilter">
            {{ showAdvancedFilter ? '收起高级筛选' : '展开高级筛选' }}
            <i :class="['el-icon-arrow-down', { 'rotate-180': showAdvancedFilter }]"></i>
          </el-button>
        </div>
      </div>

      <!-- 统计卡片 -->
      <div class="stats-container">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-value">{{ totalArticles }}</div>
            <div class="stat-label">文章总数</div>
          </div>
        </el-card>
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-value">{{ totalCategories }}</div>
            <div class="stat-label">知识分类</div>
          </div>
        </el-card>
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-value">{{ totalTags }}</div>
            <div class="stat-label">标签总数</div>
          </div>
        </el-card>
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-value">{{ recentlyAdded }}</div>
            <div class="stat-label">近期新增</div>
          </div>
        </el-card>
      </div>

      <!-- 热门文章 -->
      <div class="hot-articles-section">
        <h3>热门文章</h3>
        <el-carousel :interval="5000" type="card" height="200px">
          <el-carousel-item v-for="(article, index) in hotArticles" :key="index">
            <div class="hot-article-item" @click="viewArticle(article.id)">
              <h4>{{ article.title }}</h4>
              <p class="article-summary">{{ getSummary(article.content, 100) }}</p>
              <div class="article-meta">
                <span class="category">{{ article.category }}</span>
                <span class="view-count">{{ article.viewCount }} 次浏览</span>
              </div>
            </div>
          </el-carousel-item>
        </el-carousel>
      </div>

      <!-- 文章列表 -->
      <div class="articles-table">
        <el-table
          v-loading="loading"
          :data="articlesData"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip>
            <template #default="{ row }">
              <a href="javascript:void(0)" @click="viewArticle(row.id)">
                {{ row.title }}
              </a>
            </template>
          </el-table-column>
          <el-table-column prop="category" label="分类" width="120">
            <template #default="{ row }">
              <el-tag :type="getCategoryType(row.category)">{{ row.category }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="tags" label="标签" min-width="150">
            <template #default="{ row }">
              <el-tag 
                v-for="tag in row.tags" 
                :key="tag" 
                size="small" 
                class="tag-item"
              >
                {{ tag }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="severity" label="严重级别" width="100">
            <template #default="{ row }">
              <el-tag :type="getSeverityType(row.severity)">{{ getSeverityLabel(row.severity) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="author" label="作者" width="100" />
          <el-table-column prop="createTime" label="创建时间" width="160" />
          <el-table-column prop="lastUpdate" label="更新时间" width="160" />
          <el-table-column prop="status" label="状态" width="90">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">{{ row.status === 'draft' ? '草稿' : row.status === 'published' ? '已发布' : '已归档' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-button type="text" size="small" @click="editArticle(row.id)">编辑</el-button>
              <el-button type="text" size="small" @click="viewArticle(row.id)">查看</el-button>
              <el-dropdown @command="(command) => handleActionCommand(command, row.id)">
                <el-button type="text" size="small">
                  更多 <i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="duplicate">复制</el-dropdown-item>
                    <el-dropdown-item command="publish" v-if="row.status === 'draft'">发布</el-dropdown-item>
                    <el-dropdown-item command="archive" v-if="row.status === 'published'">归档</el-dropdown-item>
                    <el-dropdown-item command="delete" danger>删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新建/编辑文章对话框 -->
    <el-dialog
      v-model="createArticleDialogVisible"
      :title="isEditMode ? '编辑文章' : '新建文章'"
      width="80%"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="articleFormRef"
        :model="articleForm"
        :rules="articleFormRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="18">
            <el-form-item label="文章标题" prop="title">
              <el-input v-model="articleForm.title" placeholder="请输入文章标题" />
            </el-form-item>
            <el-form-item label="关键词" prop="keywords">
              <el-input v-model="articleForm.keywords" placeholder="请输入关键词，逗号分隔" />
            </el-form-item>
            <el-form-item label="内容摘要" prop="summary">
              <el-input
                v-model="articleForm.summary"
                type="textarea"
                rows="3"
                placeholder="请输入文章摘要"
              />
            </el-form-item>
            <el-form-item label="文章内容" prop="content">
              <div class="editor-container">
                <!-- 这里使用Markdown编辑器或富文本编辑器 -->
                <el-input
                  v-model="articleForm.content"
                  type="textarea"
                  rows="15"
                  placeholder="请输入文章内容（支持Markdown格式）"
                  style="font-family: monospace;"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <div class="form-sidebar">
              <el-form-item label="知识分类" prop="category">
                <el-select v-model="articleForm.category" placeholder="选择分类">
                  <el-option
                    v-for="item in categories"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="标签" prop="tags">
                <el-select
                  v-model="articleForm.tags"
                  placeholder="选择标签"
                  multiple
                  filterable
                  allow-create
                  default-first-option
                >
                  <el-option
                    v-for="item in allTags"
                    :key="item"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="严重级别" prop="severity">
                <el-select v-model="articleForm.severity" placeholder="选择严重级别">
                  <el-option
                    v-for="item in severityOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="作者" prop="author">
                <el-input v-model="articleForm.author" placeholder="请输入作者名称" />
              </el-form-item>
              <el-form-item label="状态" prop="status">
                <el-radio-group v-model="articleForm.status">
                  <el-radio value="draft">草稿</el-radio>
                  <el-radio value="published">已发布</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="相关CVE">
                <el-input
                  v-model="articleForm.relatedCve"
                  placeholder="请输入相关CVE编号，逗号分隔"
                />
              </el-form-item>
              <el-form-item label="参考链接">
                <el-input
                  v-model="articleForm.referenceLinks"
                  type="textarea"
                  rows="3"
                  placeholder="请输入参考链接，每行一个"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitArticleForm">提交</el-button>
                <el-button @click="handleDialogClose">取消</el-button>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>

    <!-- 文章详情对话框 -->
    <el-dialog
      v-model="articleDetailDialogVisible"
      :title="currentArticle.title || '文章详情'"
      width="90%"
      :close-on-click-modal="false"
      @close="closeArticleDetail"
    >
      <div class="article-detail">
        <div class="article-header">
          <h2>{{ currentArticle.title }}</h2>
          <div class="article-meta-info">
            <span class="meta-item">作者：{{ currentArticle.author }}</span>
            <span class="meta-item">创建时间：{{ currentArticle.createTime }}</span>
            <span class="meta-item">更新时间：{{ currentArticle.lastUpdate }}</span>
            <span class="meta-item">浏览次数：{{ currentArticle.viewCount }}</span>
          </div>
          <div class="article-tags">
            <el-tag 
              v-for="tag in currentArticle.tags" 
              :key="tag" 
              size="small"
            >
              {{ tag }}
            </el-tag>
          </div>
        </div>
        <div class="article-content">
          <!-- 这里使用Markdown渲染器 -->
          <div v-html="renderMarkdown(currentArticle.content)"></div>
        </div>
        <div class="article-footer">
          <div class="related-info">
            <h4>相关信息</h4>
            <div v-if="currentArticle.relatedCve" class="related-cve">
              <strong>相关CVE：</strong>
              <el-tag 
                v-for="cve in currentArticle.relatedCve.split(',')" 
                :key="cve" 
                size="small" 
                type="info"
              >
                {{ cve.trim() }}
              </el-tag>
            </div>
            <div v-if="currentArticle.referenceLinks" class="reference-links">
              <strong>参考链接：</strong>
              <ul>
                <li v-for="(link, index) in currentArticle.referenceLinks.split('\n')" :key="index">
                  <a :href="link" target="_blank">{{ link }}</a>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 导入文章对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="导入文章"
      width="600px"
      :close-on-click-modal="false"
      @close="closeImportDialog"
    >
      <el-form ref="importFormRef" :model="importForm" label-width="100px">
        <el-form-item label="导入方式">
          <el-radio-group v-model="importForm.importType">
            <el-radio value="file">文件导入</el-radio>
            <el-radio value="json">JSON格式</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="importForm.importType === 'file'" label="选择文件">
          <el-upload
            class="upload-demo"
            drag
            action=""
            :before-upload="handleFileUpload"
            multiple
            :file-list="importForm.fileList"
            :auto-upload="false"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <template #tip>
              <div class="el-upload__tip">
                支持上传 .md, .json, .txt 文件
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item v-if="importForm.importType === 'json'" label="JSON内容">
          <el-input
            v-model="importForm.jsonContent"
            type="textarea"
            rows="10"
            placeholder="请粘贴JSON格式的文章数据"
          />
        </el-form-item>
        <el-form-item label="导入选项">
          <el-checkbox v-model="importForm.overwriteExisting">覆盖已存在文章</el-checkbox>
          <el-checkbox v-model="importForm.skipDuplicates">跳过重复文章</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitImportForm">开始导入</el-button>
          <el-button @click="closeImportDialog">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import '../assets/compliance-style.css' // 复用样式文件

// 响应式数据
const loading = ref(false)
const showAdvancedFilter = ref(false)
const dateRange = ref([])
const selectedArticles = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const isEditMode = ref(false)

// 搜索表单
const searchForm = reactive({
  keyword: '',
  category: '',
  tags: [],
  severity: '',
  author: '',
  status: ''
})

// 文章表单
const articleForm = reactive({
  id: '',
  title: '',
  content: '',
  summary: '',
  keywords: '',
  category: '',
  tags: [],
  severity: '',
  author: '',
  status: 'draft',
  relatedCve: '',
  referenceLinks: ''
})

// 导入表单
const importForm = reactive({
  importType: 'file',
  fileList: [],
  jsonContent: '',
  overwriteExisting: false,
  skipDuplicates: true
})

// 对话框状态
const createArticleDialogVisible = ref(false)
const articleDetailDialogVisible = ref(false)
const importDialogVisible = ref(false)

// 表单引用
const articleFormRef = ref(null)
const importFormRef = ref(null)

// 当前文章
const currentArticle = ref({})

// 文章列表数据
const articles = ref([])

// 分类数据
const categories = ref([
  { value: '漏洞分析', label: '漏洞分析' },
  { value: '修复方案', label: '修复方案' },
  { value: '安全配置', label: '安全配置' },
  { value: '渗透测试', label: '渗透测试' },
  { value: '安全基线', label: '安全基线' },
  { value: '最佳实践', label: '最佳实践' },
  { value: '安全公告', label: '安全公告' },
  { value: '技术文档', label: '技术文档' }
])

// 所有标签
const allTags = ref([
  'Web安全', '漏洞利用', 'SQL注入', 'XSS', 'CSRF', '权限提升',
  '网络安全', '密码学', '安全架构', '安全审计', '风险评估',
  '应急响应', 'APT', '恶意软件', '威胁情报', '云安全',
  'IoT安全', '移动安全', '容器安全', 'DevSecOps'
])

// 严重级别选项
const severityOptions = ref([
  { value: 'critical', label: '严重' },
  { value: 'high', label: '高' },
  { value: 'medium', label: '中' },
  { value: 'low', label: '低' }
])

// 作者列表
const authors = ref(['系统管理员', '安全专家', '技术团队', '第三方顾问'])

// 表单验证规则
const articleFormRules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 5, max: 200, message: '标题长度在 5 到 200 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择知识分类', trigger: 'change' }
  ],
  author: [
    { required: true, message: '请输入作者名称', trigger: 'blur' }
  ]
}

// 计算属性
const totalArticles = computed(() => articles.value.length)
const totalCategories = computed(() => categories.value.length)
const totalTags = computed(() => allTags.value.length)
const recentlyAdded = computed(() => {
  const today = new Date()
  today.setDate(today.getDate() - 7) // 最近7天
  return articles.value.filter(article => new Date(article.createTime) >= today).length
})

const articlesData = computed(() => {
  // 这里应该根据筛选条件过滤数据，现在返回所有数据作为演示
  return articles.value
})

const hotArticles = computed(() => {
  // 根据浏览次数排序，取前5条
  return [...articles.value]
    .sort((a, b) => b.viewCount - a.viewCount)
    .slice(0, 5)
})

// 辅助函数
const getCategoryType = (category) => {
  const typeMap = {
    '漏洞分析': 'danger',
    '修复方案': 'success',
    '安全配置': 'warning',
    '渗透测试': 'info',
    '安全基线': 'primary',
    '最佳实践': 'success',
    '安全公告': 'warning',
    '技术文档': 'info'
  }
  return typeMap[category] || 'info'
}

const getSeverityLabel = (severity) => {
  const labelMap = {
    'critical': '严重',
    'high': '高',
    'medium': '中',
    'low': '低'
  }
  return labelMap[severity] || '未知'
}

const getSeverityType = (severity) => {
  const typeMap = {
    'critical': 'danger',
    'high': 'danger',
    'medium': 'warning',
    'low': 'info'
  }
  return typeMap[severity] || 'info'
}

const getStatusType = (status) => {
  const typeMap = {
    'draft': 'info',
    'published': 'success',
    'archived': 'warning'
  }
  return typeMap[status] || 'info'
}

const getSummary = (content, length) => {
  if (!content) return ''
  const plainText = content.replace(/#+\s/g, '').replace(/\*\*(.*?)\*\*/g, '$1').replace(/\*(.*?)\*/g, '$1')
  return plainText.length > length ? plainText.substring(0, length) + '...' : plainText
}

const renderMarkdown = (content) => {
  // 简单的Markdown渲染，实际项目中应使用专业的Markdown渲染库
  if (!content) return ''
  let html = content
    .replace(/^# (.*$)/gm, '<h1>$1</h1>')
    .replace(/^## (.*$)/gm, '<h2>$1</h2>')
    .replace(/^### (.*$)/gm, '<h3>$1</h3>')
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.*?)\*/g, '<em>$1</em>')
    .replace(/```([\s\S]*?)```/g, '<pre><code>$1</code></pre>')
    .replace(/`(.*?)`/g, '<code>$1</code>')
    .replace(/\n/g, '<br>')
  return html
}

// 模拟数据
const generateMockData = () => {
  const mockArticles = [
    {
      id: 1,
      title: 'SQL注入漏洞分析与防护',
      content: `# SQL注入漏洞分析与防护\n\n## 什么是SQL注入？\n\nSQL注入是一种常见的Web安全漏洞，攻击者通过在用户输入中插入恶意SQL代码，使应用程序执行非预期的数据库操作。\n\n## 漏洞原理\n\n当应用程序直接将用户输入拼接到SQL查询语句中，而没有进行适当的验证和转义时，就可能导致SQL注入。\n\n## 防护措施\n\n1. 使用参数化查询/预处理语句\n2. 实施输入验证\n3. 使用ORM框架\n4. 最小权限原则\n5. 定期进行安全审计`,
      summary: '本文详细介绍了SQL注入漏洞的原理、危害以及防护措施，包括参数化查询、输入验证等关键安全实践。',
      keywords: 'SQL注入, 数据库安全, 参数化查询, 输入验证',
      category: '漏洞分析',
      tags: ['Web安全', 'SQL注入', '数据库安全'],
      severity: 'high',
      author: '安全专家',
      createTime: '2024-01-15 10:30:00',
      lastUpdate: '2024-01-15 10:30:00',
      status: 'published',
      viewCount: 1523,
      relatedCve: 'CVE-2023-25136, CVE-2023-25143',
      referenceLinks: 'https://owasp.org/www-community/attacks/SQL_Injection\nhttps://portswigger.net/web-security/sql-injection'
    },
    {
      id: 2,
      title: 'XSS漏洞详解与修复指南',
      content: `# XSS漏洞详解与修复指南\n\n## 跨站脚本攻击(XSS)概述\n\nXSS是一种注入型攻击，攻击者在受信任的网站中注入恶意脚本，当其他用户浏览页面时，脚本会在用户的浏览器中执行。\n\n## XSS的三种类型\n\n1. **存储型XSS**：恶意代码存储在目标服务器中\n2. **反射型XSS**：恶意代码包含在URL中\n3. **DOM型XSS**：漏洞存在于客户端代码中\n\n## 修复方案\n\n1. 输入验证与过滤\n2. 输出编码\n3. 内容安全策略(CSP)\n4. 使用现代框架的自动转义功能`,
      summary: '本文详细讲解了XSS漏洞的类型、原理、危害以及全面的修复方案，帮助开发者有效防范跨站脚本攻击。',
      keywords: 'XSS, 跨站脚本, 前端安全, 内容安全策略',
      category: '修复方案',
      tags: ['Web安全', 'XSS', '前端安全'],
      severity: 'high',
      author: '技术团队',
      createTime: '2024-01-12 14:20:00',
      lastUpdate: '2024-01-12 14:20:00',
      status: 'published',
      viewCount: 1287,
      relatedCve: 'CVE-2023-21674',
      referenceLinks: 'https://owasp.org/www-community/attacks/xss/\nhttps://portswigger.net/web-security/cross-site-scripting'
    },
    {
      id: 3,
      title: '服务器安全配置最佳实践',
      content: `# 服务器安全配置最佳实践\n\n## 系统加固\n\n1. 定期更新系统和软件包\n2. 关闭不必要的服务和端口\n3. 使用防火墙限制网络访问\n\n## 用户管理\n\n1. 禁用root远程登录\n2. 使用SSH密钥认证\n3. 实施强密码策略\n\n## 日志监控\n\n1. 配置集中式日志管理\n2. 设置关键事件告警\n3. 定期审计日志`,
      summary: '本文提供了全面的服务器安全配置指南，涵盖系统加固、用户管理、日志监控等多个方面的最佳实践。',
      keywords: '服务器安全, 系统加固, 防火墙, SSH, 日志监控',
      category: '安全配置',
      tags: ['网络安全', '系统安全', '最佳实践'],
      severity: 'medium',
      author: '系统管理员',
      createTime: '2024-01-10 09:15:00',
      lastUpdate: '2024-01-10 09:15:00',
      status: 'published',
      viewCount: 956,
      relatedCve: '',
      referenceLinks: 'https://cisecurity.org/benchmark/'
    },
    {
      id: 4,
      title: '企业网络安全架构设计指南',
      content: `# 企业网络安全架构设计指南\n\n## 分层防御策略\n\n1. 边界安全\n2. 网络分段\n3. 内部安全控制\n\n## 核心组件\n\n1. 下一代防火墙\n2. 入侵检测/防御系统\n3. 安全信息与事件管理(SIEM)\n\n## 设计原则\n\n1. 深度防御\n2. 最小权限\n3. 零信任架构`,
      summary: '本文提供了企业级网络安全架构的设计原则和实施方案，帮助组织建立全面的网络安全防御体系。',
      keywords: '网络安全, 架构设计, 分层防御, 零信任',
      category: '最佳实践',
      tags: ['网络安全', '安全架构', '最佳实践'],
      severity: 'medium',
      author: '第三方顾问',
      createTime: '2024-01-08 16:45:00',
      lastUpdate: '2024-01-08 16:45:00',
      status: 'published',
      viewCount: 782,
      relatedCve: '',
      referenceLinks: 'https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-53r5.pdf'
    },
    {
      id: 5,
      title: 'OWASP Top 10 2023解读',
      content: `# OWASP Top 10 2023解读\n\n## 最新版Top 10主要变化\n\n1. 新增了几个关键风险类别\n2. 更新了风险评估方法\n3. 反映了当前Web应用安全态势\n\n## 重点关注项\n\n1. 失效的访问控制\n2. 加密机制失效\n3. 安全配置错误\n\n## 防御策略\n\n针对每类风险的具体防御措施和最佳实践`,
      summary: '本文对OWASP Top 10 2023版进行了详细解读，分析了最新的Web应用安全风险趋势和防御策略。',
      keywords: 'OWASP, Web安全, 风险评估, 安全趋势',
      category: '安全公告',
      tags: ['Web安全', 'OWASP', '风险评估'],
      severity: 'high',
      author: '安全专家',
      createTime: '2024-01-05 11:30:00',
      lastUpdate: '2024-01-05 11:30:00',
      status: 'published',
      viewCount: 2156,
      relatedCve: '',
      referenceLinks: 'https://owasp.org/www-project-top-ten/'
    }
  ]
  
  articles.value = mockArticles
  total.value = mockArticles.length
}

// 方法函数
const fetchArticles = async () => {
  loading.value = true
  try {
    // 模拟API调用
    // const response = await apiService.getArticles({ ...searchForm, page: currentPage.value, pageSize: pageSize.value })
    // articles.value = response.data
    // total.value = response.total
    
    // 使用模拟数据
    generateMockData()
  } catch (error) {
    ElMessage.error('获取文章列表失败')
    console.error('Failed to fetch articles:', error)
  } finally {
    loading.value = false
  }
}

const fetchArticleDetail = async (articleId) => {
  loading.value = true
  try {
    // 模拟API调用
    // const response = await apiService.getArticleDetail(articleId)
    // currentArticle.value = response
    
    // 从模拟数据中查找
    currentArticle.value = articles.value.find(article => article.id === articleId)
    
    if (currentArticle.value) {
      // 增加浏览次数
      currentArticle.value.viewCount += 1
    }
  } catch (error) {
    ElMessage.error('获取文章详情失败')
    console.error('Failed to fetch article detail:', error)
  } finally {
    loading.value = false
  }
}

const createArticle = async (formData) => {
  loading.value = true
  try {
    // 模拟API调用
    // const response = await apiService.createArticle(formData)
    
    // 添加到模拟数据
    const newArticle = {
      ...formData,
      id: Date.now(),
      createTime: new Date().toLocaleString('zh-CN'),
      lastUpdate: new Date().toLocaleString('zh-CN'),
      viewCount: 0
    }
    
    articles.value.unshift(newArticle)
    total.value += 1
    
    ElMessage.success('文章创建成功')
  } catch (error) {
    ElMessage.error('文章创建失败')
    console.error('Failed to create article:', error)
  } finally {
    loading.value = false
  }
}

const updateArticle = async (formData) => {
  loading.value = true
  try {
    // 模拟API调用
    // const response = await apiService.updateArticle(formData.id, formData)
    
    // 更新模拟数据
    const index = articles.value.findIndex(article => article.id === formData.id)
    if (index !== -1) {
      articles.value[index] = {
        ...articles.value[index],
        ...formData,
        lastUpdate: new Date().toLocaleString('zh-CN')
      }
    }
    
    ElMessage.success('文章更新成功')
  } catch (error) {
    ElMessage.error('文章更新失败')
    console.error('Failed to update article:', error)
  } finally {
    loading.value = false
  }
}

const deleteArticle = async (articleId) => {
  loading.value = true
  try {
    // 模拟API调用
    // const response = await apiService.deleteArticle(articleId)
    
    // 从模拟数据中删除
    const index = articles.value.findIndex(article => article.id === articleId)
    if (index !== -1) {
      articles.value.splice(index, 1)
      total.value -= 1
    }
    
    ElMessage.success('文章删除成功')
  } catch (error) {
    ElMessage.error('文章删除失败')
    console.error('Failed to delete article:', error)
  } finally {
    loading.value = false
  }
}

const publishArticle = async (articleId) => {
  loading.value = true
  try {
    // 模拟API调用
    // const response = await apiService.publishArticle(articleId)
    
    // 更新模拟数据
    const article = articles.value.find(a => a.id === articleId)
    if (article) {
      article.status = 'published'
    }
    
    ElMessage.success('文章已发布')
  } catch (error) {
    ElMessage.error('发布失败')
    console.error('Failed to publish article:', error)
  } finally {
    loading.value = false
  }
}

const archiveArticle = async (articleId) => {
  loading.value = true
  try {
    // 模拟API调用
    // const response = await apiService.archiveArticle(articleId)
    
    // 更新模拟数据
    const article = articles.value.find(a => a.id === articleId)
    if (article) {
      article.status = 'archived'
    }
    
    ElMessage.success('文章已归档')
  } catch (error) {
    ElMessage.error('归档失败')
    console.error('Failed to archive article:', error)
  } finally {
    loading.value = false
  }
}

const duplicateArticle = async (articleId) => {
  loading.value = true
  try {
    // 模拟API调用
    // const response = await apiService.duplicateArticle(articleId)
    
    // 从模拟数据中复制
    const originalArticle = articles.value.find(a => a.id === articleId)
    if (originalArticle) {
      const newArticle = {
        ...originalArticle,
        id: Date.now(),
        title: `${originalArticle.title} (副本)`,
        status: 'draft',
        createTime: new Date().toLocaleString('zh-CN'),
        lastUpdate: new Date().toLocaleString('zh-CN'),
        viewCount: 0
      }
      articles.value.unshift(newArticle)
      total.value += 1
    }
    
    ElMessage.success('文章已复制')
  } catch (error) {
    ElMessage.error('复制失败')
    console.error('Failed to duplicate article:', error)
  } finally {
    loading.value = false
  }
}

const importArticles = async () => {
  loading.value = true
  try {
    // 模拟API调用
    // const response = await apiService.importArticles(importForm)
    
    ElMessage.success('文章导入成功')
    fetchArticles()
  } catch (error) {
    ElMessage.error('文章导入失败')
    console.error('Failed to import articles:', error)
  } finally {
    loading.value = false
  }
}

const exportArticles = async () => {
  loading.value = true
  try {
    // 模拟API调用
    // const response = await apiService.exportArticles({ ...searchForm })
    
    ElMessage.success('文章导出成功')
  } catch (error) {
    ElMessage.error('文章导出失败')
    console.error('Failed to export articles:', error)
  } finally {
    loading.value = false
  }
}

// 事件处理函数
const handleSearch = () => {
  currentPage.value = 1
  fetchArticles()
}

const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    if (Array.isArray(searchForm[key])) {
      searchForm[key] = []
    } else {
      searchForm[key] = ''
    }
  })
  dateRange.value = []
  currentPage.value = 1
  fetchArticles()
}

const toggleAdvancedFilter = () => {
  showAdvancedFilter.value = !showAdvancedFilter.value
}

const handleSelectionChange = (selection) => {
  selectedArticles.value = selection
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
  fetchArticles()
}

const handleCurrentChange = (newCurrent) => {
  currentPage.value = newCurrent
  fetchArticles()
}

const handleHeaderCommand = (command) => {
  switch (command) {
    case 'importArticles':
      openImportDialog()
      break
    case 'exportArticles':
      exportArticles()
      break
    case 'refresh':
      fetchArticles()
      break
  }
}

const handleActionCommand = (command, articleId) => {
  switch (command) {
    case 'delete':
      confirmDeleteArticle(articleId)
      break
    case 'publish':
      publishArticle(articleId)
      break
    case 'archive':
      archiveArticle(articleId)
      break
    case 'duplicate':
      duplicateArticle(articleId)
      break
  }
}

const openCreateArticleDialog = () => {
  isEditMode.value = false
  resetArticleForm()
  createArticleDialogVisible.value = true
}

const editArticle = (articleId) => {
  isEditMode.value = true
  const article = articles.value.find(a => a.id === articleId)
  if (article) {
    Object.assign(articleForm, {
      ...article
    })
  }
  createArticleDialogVisible.value = true
}

const viewArticle = async (articleId) => {
  await fetchArticleDetail(articleId)
  articleDetailDialogVisible.value = true
}

const openImportDialog = () => {
  resetImportForm()
  importDialogVisible.value = true
}

const handleDialogClose = () => {
  createArticleDialogVisible.value = false
  resetArticleForm()
}

const closeArticleDetail = () => {
  articleDetailDialogVisible.value = false
  currentArticle.value = {}
}

const closeImportDialog = () => {
  importDialogVisible.value = false
  resetImportForm()
}

const submitArticleForm = () => {
  articleFormRef.value.validate(async (valid) => {
    if (valid) {
      if (isEditMode.value) {
        await updateArticle({ ...articleForm })
      } else {
        await createArticle({ ...articleForm })
      }
      createArticleDialogVisible.value = false
      resetArticleForm()
    }
  })
}

const resetArticleForm = () => {
  if (articleFormRef.value) {
    articleFormRef.value.resetFields()
  }
  Object.assign(articleForm, {
    id: '',
    title: '',
    content: '',
    summary: '',
    keywords: '',
    category: '',
    tags: [],
    severity: '',
    author: '',
    status: 'draft',
    relatedCve: '',
    referenceLinks: ''
  })
}

const submitImportForm = () => {
  importFormRef.value.validate(async () => {
    await importArticles()
    importDialogVisible.value = false
    resetImportForm()
  })
}

const resetImportForm = () => {
  if (importFormRef.value) {
    importFormRef.value.resetFields()
  }
  Object.assign(importForm, {
    importType: 'file',
    fileList: [],
    jsonContent: '',
    overwriteExisting: false,
    skipDuplicates: true
  })
}

const handleFileUpload = (file) => {
  // 处理文件上传，实际项目中应使用合适的上传方式
  console.log('File to upload:', file)
  return false // 阻止默认上传
}

const confirmDeleteArticle = (articleId) => {
  ElMessageBox.confirm(
    '确定要删除这篇文章吗？此操作不可撤销。',
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    }
  ).then(() => {
    deleteArticle(articleId)
  }).catch(() => {
    // 用户取消操作
  })
}

// 生命周期钩子
onMounted(() => {
  fetchArticles()
})
</script>